package com.web.system.action;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.util.BaseActionUtil;
import com.util.MD5Util;
import com.web.system.po.LoginPo;
import com.web.system.po.UserPo;
import com.web.system.service.UserService;
@Controller @Scope("prototype") 
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "loginAction",results={
		@Result(name="input",type="redirect", location="/login.jsp"),
		@Result(name="success",location="/jsp/index.jsp")
})
public class LoginAction extends BaseActionUtil implements ModelDriven<LoginPo> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4497442039825358213L;

	@Resource
	private UserService userService;
	
	private LoginPo login;

	public LoginPo getModel() {
		// TODO Auto-generated method stub
		login = new LoginPo();
		return login;
	}

	public String xxx() throws Exception {
		session.setAttribute("time", 6000);
		out.print("success");
		return NONE;
	}
	/**
	 * 检查用户名与密码是否正确
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkLogin() throws Exception {

		int flag = 0;
		
		String verificationCode = session.getAttribute("verificationCode") + "";
		login.setPassword(MD5Util.getEncryptPsw(login.getPassword()));
		if (!verificationCode.equalsIgnoreCase(login.getVerificationCode())) {
			out.print("0");//验证码错误
			flag = 1;
		} else {
			if (!userService.checkLogin(login)) {
				out.print("1");//用户名或者密码错误
			} else {
				flag = 1;
				session.removeAttribute("count");
				UserPo user = userService.getUserByLogin(login);
					session.setAttribute("user", user);
					out.print("2");//成功登录
			}
		}
		if (flag == 0) {
			String count = session.getAttribute("count") + "";
			if ("".equalsIgnoreCase(count) || "null".equalsIgnoreCase(count)
					|| count == null) {
				session.setAttribute("count", 1);
			} else {
				if(Integer.parseInt(count) > 3){
					out.print("3");//超过三次登录
				}else {
					session.setAttribute("count", Integer.parseInt(count) + 1);
				}
			}
		}
		out.flush();
		out.close();
		return NONE;
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 * @throws Exception
	 */
	public String logout() throws Exception {
		session.removeAttribute("user");
		session.invalidate();
		return "input";
	}

	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
